package com.pes.arcww.dao;

import java.util.Collection;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Repository;
import com.pes.arcww.form.Users;

@Repository
public class UsersDAOImpl implements UsersDAO{

	@Autowired
	private SessionFactory sessionFactory;
	
	public void addUser(Users user) {
		sessionFactory.getCurrentSession().save(user);
	}

	@SuppressWarnings("unchecked")
	public Collection<Users> listUsers(String filter, String value) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(Users.class);
		
		if(filter.equals("") && value.equals("")){
			criteria.addOrder(Order.asc("email"));
		}else if(filter.equals("id")){
			criteria.add(Restrictions.like("email", "%"+value+"%")).addOrder(Order.asc("email"));
		}else if(filter.equals("firstname")){
			criteria.add(Restrictions.like("firstName", "%"+value+"%")).addOrder(Order.asc("firstName"));
		}else if(filter.equals("lastname")){
			criteria.add(Restrictions.like("lastName", "%"+value+"%")).addOrder(Order.asc("lastName"));
		}else if(filter.equals("badge")){
			criteria.add(Restrictions.like("badgeID", "%"+value+"%")).addOrder(Order.asc("badgeID"));
		}

		return criteria.list();
		
	}

	public void removeUser(String email) {
		Users user = getUser(email);
		if(user != null){
			sessionFactory.getCurrentSession().delete(user);
		}
	}

	public void updateUser(Users user) {
		sessionFactory.getCurrentSession().update(user);
	}

	public Users getUser(String email) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Users user = (Users) session.get(Users.class, email);
		Hibernate.initialize(user.getExamsList());
		session.getTransaction().commit();
		session.close();
		return user;
	}

	public Boolean validate(String email, String password) {
		Users user = getUser(email);
		if(null != user){
			if(BCrypt.checkpw(password, user.getPassword())){
				return true;
			}
		}
		return false;
	}
}
